using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Navigation;
using System.Threading;
using System.Linq;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;

namespace SlamCms.SharePoint.Tagging.Features
{
	/// <summary>
	/// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
	/// </summary>
	/// <remarks>
	/// The GUID attached to this class may be used during packaging and should not be modified.
	/// </remarks>

	[Guid("a363be94-3808-46d9-a42a-b919eff65bb6")]
	public class TagEngineProvisioningHandler : SPFeatureReceiver
	{
		public override void FeatureActivated(SPFeatureReceiverProperties properties)
		{
			SPSite site = properties.Feature.Parent as SPSite;
			using (SPWeb globalSettingsWeb = site.AllWebs["GlobalSettings"])
			{
				Guid pagesFeatureId = new Guid("24902a6e-ed53-4753-98b4-e50cd10683cc");

				if (globalSettingsWeb.Features[pagesFeatureId] == null)
				{
					globalSettingsWeb.Features.Add(pagesFeatureId);
					globalSettingsWeb.Update();
				}
			}
		}

		public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
		{
			base.FeatureDeactivating(properties);
		
			SPSite site = properties.Feature.Parent as SPSite;
			using (SPWeb globalSettingsWeb = site.AllWebs["GlobalSettings"])
			{
				Guid pagesFeatureId = new Guid("24902a6e-ed53-4753-98b4-e50cd10683cc");

				if (globalSettingsWeb.Features[pagesFeatureId] != null)
				{
					globalSettingsWeb.Features.Remove(pagesFeatureId);
					globalSettingsWeb.Update();
				}
			}
		}

		public override void FeatureInstalled(SPFeatureReceiverProperties properties)
		{
			SPWebService service = SPWebService.ContentService;
			SPWcfServiceSettings settings = new SPWcfServiceSettings();
			settings.ReaderQuotasMaxStringContentLength = Int32.MaxValue;
			settings.ReaderQuotasMaxArrayLength = Int32.MaxValue;
			settings.ReaderQuotasMaxBytesPerRead = Int32.MaxValue;
			settings.MaxReceivedMessageSize = Int32.MaxValue;
			settings.MaxBufferSize = Int32.MaxValue;
			settings.ReaderQuotasMaxBytesPerRead = Int32.MaxValue;
			settings.ReaderQuotasMaxDepth = Int32.MaxValue;
			settings.ReaderQuotasMaxNameTableCharCount = Int32.MaxValue;

			service.WcfServiceSettings["TagTreeManagerService.svc"] = settings;

			service.Update(true);
		}

		public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
		{
		}
	}
}
